/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.monitor.zabbix.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.monitor.zabbix.ZabbixConstant;
import com.monitor.zabbix.service.ZabbixApiService;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.Dict;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;

/**
 * 资产管理Controller
 * 
 * @author johnKee
 * @version 2016-07-20
 */
@Controller
@RequestMapping(value = "${adminPath}/zabbix/api")
public class ZabbixApiController extends BaseController {

	private static final Logger logger = LoggerFactory
			.getLogger(ZabbixApiController.class);

	@Autowired
	private ZabbixApiService zabbixApiService;

	/**
	 * 创建主机
	 * 
	 * @return
	 */

	@ResponseBody
	@RequestMapping(value = { "host.create" })
	public Map<String, Object> createHost(
			@RequestParam Map<String, Object> map, HttpServletRequest request,
			HttpServletResponse response) {
		String uri = request.getRequestURI();
		logger.info(String.format("uri 创建主机:%s", uri), map);
		String message = ZabbixConstant.OPERATION_SUCCESS;
		String status = "S";
		try {
			map = zabbixApiService.createHost(map);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			message = ZabbixConstant.SYSTEM_ERROR;
			status = "F";
		}
		map.put("status", status);
		map.put("message", message);

		return map;
	}

	/**
	 * 历史数据查询
	 * 
	 * @param map
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = { "history.get" })
	public Map<String, Object> getHistoryData(
			@RequestParam Map<String, Object> map, HttpServletRequest request,
			HttpServletResponse response) {
		String uri = request.getRequestURI();
		logger.info(String.format("uri  历史数据查询:%s", uri), map);
		String message = ZabbixConstant.OPERATION_SUCCESS;
		String status = "S";
		try {

			Map<String, String> itemKeyMap = new HashMap<>();
			if (map.containsKey("hostid")) {
				String hostid = map.get("hostid").toString();
				Map<String, Object> itemMap = new HashMap<>();
				itemMap.put("hostids", hostid);
				if (map.containsKey("key")) {
					Map<String, Object> searchMap = new HashMap<>();
					searchMap.put("key_", map.get("key"));
					itemMap.put("search", searchMap);
				}

				Map<String, Object> retItemMap = zabbixApiService
						.getItem(itemMap);
				List<String> itemIds = new ArrayList<>();

				if (retItemMap.containsKey("result")) {

					List<JSONObject> list = (List<JSONObject>) retItemMap
							.get("result");
					for (JSONObject json : list) {
						String itemId = json.get("itemid").toString();
						itemIds.add(itemId);
						itemKeyMap.put(itemId, json.get("key_").toString());
					}
					map.put("itemids", itemIds);
				}
			}

			map = zabbixApiService.getHistoryData(map);
			if (map.containsKey("result")) {
				List<JSONObject> list = (List<JSONObject>) map.get("result");
				for (JSONObject json : list) {
					String itemId = json.get("itemid").toString();
					String key = itemKeyMap.get(itemId);
					json.put("key", key);
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			message = ZabbixConstant.SYSTEM_ERROR;
			status = "F";
		}
		map.put("status", status);
		map.put("message", message);

		return map;
	}

	/**
	 * 查询主机状态
	 * 
	 * @param map
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = { "host.get" })
	public Map<String, Object> getHost(@RequestParam Map<String, Object> map,
			HttpServletRequest request, HttpServletResponse response) {
		String uri = request.getRequestURI();
		logger.info(String.format("uri  查询主机状态:%s", uri), map);
		String message = ZabbixConstant.OPERATION_SUCCESS;
		String status = "S";
		try {
			if (!map.containsKey("output")) {
				map.put("output", new String[] { "hostid", "host", "available",
						"status", "name", "ip", "port" });
			}
			Map<String, Object> retHostMap = zabbixApiService.getHost(map);

			List<Map<String, Object>> problems = zabbixApiService
					.findProblem(map);
			Map<String, Map<String, Object>> hostMap = new HashMap<>();
			for (Map<String, Object> thisMap : problems) {
				hostMap.put(thisMap.get("hostid").toString(), thisMap);
			}

			if (retHostMap.containsKey("result")) {
				List<JSONObject> list = (List<JSONObject>) retHostMap
						.get("result");
				for (JSONObject json : list) {
					if ("2".equals(json.get("available"))) {
						continue;
					}
					String hostid = json.get("hostid").toString();
					if (hostMap.containsKey(hostid)) {
						json.put("war", "1");
					} else {
						json.put("war", "0");
					}
				}
				map.put("result", list);
			}

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			message = ZabbixConstant.SYSTEM_ERROR;
			status = "F";
		}
		map.put("status", status);
		map.put("message", message);

		return map;
	}

	/**
	 * 查询主机状态
	 * 
	 * @param map
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = { "login" })
	public Map<String, Object> login(@RequestParam Map<String, Object> map,
			HttpServletRequest request, HttpServletResponse response) {
		String uri = request.getRequestURI();
		logger.info(String.format("uri  登录:%s", uri), map);
		String message = ZabbixConstant.OPERATION_SUCCESS;
		String status = "S";
		try {
			map = zabbixApiService.login(map);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			message = ZabbixConstant.SYSTEM_ERROR;
			status = "F";
		}
		map.put("status", status);
		map.put("message", message);

		return map;
	}

	/**
	 * 查询主机监控项
	 * 
	 * @return
	 */

	@ResponseBody
	@RequestMapping(value = { "item.get" })
	public Map<String, Object> getItem(@RequestParam Map<String, Object> map,
			HttpServletRequest request, HttpServletResponse response) {
		String uri = request.getRequestURI();
		logger.info(String.format("uri 创建主机:%s", uri), map);
		String message = ZabbixConstant.OPERATION_SUCCESS;
		String status = "S";
		try {
			if (map.containsKey("key")) {
				Map<String, Object> searchMap = new HashMap<>();
				searchMap.put("key_", map.get("key"));
				map.put("search", searchMap);
			}

			map.put("output", new String[] { "itemid", "key_", "hostid" });
			map = zabbixApiService.getItem(map);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			message = ZabbixConstant.SYSTEM_ERROR;
			status = "F";
		}
		map.put("status", status);
		map.put("message", message);

		return map;
	}

	/**
	 * 历史数据查询
	 * 
	 * @param map
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	// http://127.0.0.1:8080/zoomSite/a/zabbix/api/history.view?hostid=10107&type=type_windows&hostname=guoxc
	@RequestMapping(value = { "history.view" })
	public String historyView(@RequestParam Map<String, Object> map,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {

		String uri = request.getRequestURI();
		logger.info(String.format("uri  历史数据查询:%s", uri), map);
		if (!map.containsKey("type") || !map.containsKey("hostName")) {
			throw new RuntimeException("参数不正确！");
		}

		String hostName = map.get("hostName").toString();
		model.addAttribute("hostName", hostName);

		Map<String, Object> hostParaMap = new HashMap<String, Object>();
		hostParaMap.put("host", hostName);
		List<Map<String, Object>> hostList = zabbixApiService
				.findHostByMap(hostParaMap);
		if (hostList == null || hostList.size() == 0) {
			throw new RuntimeException("主机名称不正确！");
		}
		Map<String, Object> hostMap = hostList.get(0);
		map.put("hostid", hostMap.get("hostid"));
		String type = map.get("type").toString();
		model.addAttribute("type", map.get("type"));
		List<Dict> dictList = DictUtils.getDictList(type);
		model.addAttribute("keys", dictList);

		if (!map.containsKey("hostid") || !map.containsKey("key")) {
			return "zabbix/histroyList";
		}

		for (Dict dict : dictList) {
			String key = map.get("key").toString();
			if (key.equals(dict.getValue())) {
				model.addAttribute("keyLabel", dict.getLabel());
				break;
			}
		}

		Page<Map<String, Object>> page = zabbixApiService.findHistoryData(
				new Page<Map<String, Object>>(request, response), map);
		model.addAttribute("page", page);
		for (Map<String, Object> thisMap : page.getList()) {
			if (thisMap.containsKey("clock")) {
				long clock = Long.parseLong(thisMap.get("clock").toString());
				thisMap.put("clock", new Date(clock));
			}
		}
		model.addAttribute("map", map);
		return "zabbix/histroyList";
	}

}
